package main

import (
	"github.com/go-ini/ini"
	"github.com/sirupsen/logrus"
	"strings"
	"tym.com/LogCollection/elasticsearch"
	"tym.com/LogCollection/etcd"
	"tym.com/LogCollection/influxdb"
	"tym.com/LogCollection/mq"
	"tym.com/LogCollection/ps"
	"tym.com/LogCollection/tails"
	"tym.com/LogCollection/transfer"
	"tym.com/LogCollection/util"
)

func main() {
	var err error
	appConfig, err := ini.Load("./conf/config.ini")
	if err != nil {
		logrus.Error("initialize: config.ini failed!", err)
		return
	}

	//初始化kafka
	appConfig.Section("kafka").MapTo(&mq.KafkaConfig)
	err = mq.InitKafkaProducer()
	if err != nil {
		logrus.Error("kafka: kafka initialize config failed!", err)
		return
	}
	logrus.Info("init kafka success!")

	//初始化etcd 并从etcd获取路径
	appConfig.Section("etcd").MapTo(&etcd.Config)
	etcd.Config.LogKey = strings.Replace(etcd.Config.LogKey, "%s", util.GetLocalIP(), 1)
	err = etcd.InitConfig()

	if err != nil {
		logrus.Error("etcd: etcd initialize config failed!", err)
		return
	}
	logrus.Info("init etcd success!\n")

	//初始化tail
	var jsonLog string
	jsonLog, err = etcd.Get(etcd.Config.LogKey)
	if err != nil {
		logrus.Errorf("etcd: get key :%s is failed!, %s\n", etcd.Config.LogKey, err)
		return
	}
	// 初始化需要监听的文件
	//开启监听
	err = tails.InitTailTask(jsonLog)
	tails.TailTaskRun()

	//etcd 远程监听本服务器需要监听的文件
	etcd.Watch(etcd.Config.LogKey, tails.TailTaskWatch)
	if err != nil {
		logrus.Error("tails:", err)
		return
	}
	logrus.Info("init tails success")
	//初始化ElasticSearch
	appConfig.Section("elasticsearch").MapTo(&elasticsearch.EsConfig)
	err = elasticsearch.InitElasticSearch()
	if err != nil {
		logrus.Error("elasticsearch: init failed!", err)
		return
	}
	mq.InitKafkaConsumer()
	mq.KafkaRecd(elasticsearch.EsConfig.WatchTopic, transfer.DisposeToES)

	//初始化influxdb
	appConfig.Section("influxdb").MapTo(&influxdb.InfluxConfig)
	err = influxdb.InitInfluxData()
	if err != nil {
		logrus.Error("influxdb:", err)
	}
	//ps start
	ps.Run()

	select {}
}
